以下是我在撰寫 HCL 時常會用到的函數將一一做介紹。
locals {
list1 = ["apple", "banana"]
list2 = ["cherry", "date"]
concatenated_list = concat(local.list1, local.list2)
}
locals {
fruits = ["apple", "banana", "cherry"]
has_banana = contains(local.fruits, "banana")
}
locals {
nested_list = [["apple", "banana"], ["cherry", "date"]]
flat_list = flatten(local.nested_list)
}
locals {
fruits = ["apple", "banana", "cherry"]
num_fruits = length(local.fruits)
}
locals {
fruit_list = list("apple", "banana", "cherry")
}
locals {
fruit_colors = {
"apple" = "red",
"banana" = "yellow"
}
apple_color = lookup(local.fruit_colors, "apple", "unknown")
grape_color = lookup(local.fruit_colors, "grape", "unknown")
}
locals {
single_element_list = ["only"]
multiple_elements_list = ["one", "two"]
single_element = one(local.single_element_list)
no_single_element = one(local.multiple_elements_list)
}
以上是一些常用到的 HCL 函數,可以幫助你在 Terraform 配置中執行各種操作,從列表操作到查找、合併等。
根據你的需求,你可以選擇適合的函數來簡化配置的處理,後面文章的範例也會大量使用到這些函式。